package com.example.urmsadmin.Util;

import com.example.urmsadmin.controller.SysMenuController;
import com.example.urmsadmin.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

@Service("per")
public class PermissionService
{
    /** 所有权限标识 */
    private static final String ALL_PERMISSION = "*:*:*";

    @Autowired
    SysMenuController menuController;

    @Autowired
    private HttpServletRequest request;

    /**
     * 验证用户是否具备某权限
     * 
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean hasPermi(String permission)
    {
        if (permission == null || "".equals(permission))
        {
            return false;
        }
        CommonResult<Object> resData = menuController.getPermissions(request);
        if(resData.getData() != null){
            return hasPermissions((Set<String>)resData.getData(), permission);
        }
        return false;
    }

    /**
     * 判断是否包含权限
     * 
     * @param permissions 权限列表
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(Set<String> permissions, String permission)
    {
        return permissions.contains(ALL_PERMISSION) || permissions.contains(permission.trim());
    }
}
